#include "engine.h"
#include "vertexdeclaration.h"
#include <gl/glew.h>

uint32 vertexdeclaration_t::generate_hwid()
{
	uint32 hwid;
	glGenVertexArrays(1,&hwid);
	GLASSERT;
	glBindVertexArray(hwid);
	GLASSERT;

	unsigned offset=0;
	for (uint32 n=0; n<elementlist.size(); ++n)
	{
		glVertexAttribPointer(n,elementlist[n].elemnum,elementlist[n].type,elementlist[n].type!=GL_FLOAT,vertexsize,(void*)offset);
		GLASSERT;
		glEnableVertexAttribArray(n);
		GLASSERT;
		offset+=elementlist[n].size;
	}
	glBindVertexArray(0);

	return hwid;
}
void vertexdeclaration_t::set(uint32 _offset)
{
	unsigned offset=_offset;
	for (uint32 n=0; n<elementlist.size(); ++n)
	{
		glVertexAttribPointer(n,elementlist[n].elemnum,elementlist[n].type,elementlist[n].type!=GL_FLOAT,vertexsize,(void*)offset);
		GLASSERT;
		glEnableVertexAttribArray(n);
		GLASSERT;
		offset+=elementlist[n].size;
	}
}

void vertexdeclaration_t::generate(const stringhash& name,vertexelement_t* elem,int elemnum)
{
	this->name=name;

	vertexsize=0;
	elementlist.resize(elemnum);
	flag=0;
	for (int n=0; n<elemnum; ++n)
	{
		elementlist[n]=elem[n];
		vertexsize+=elem[n].size;
		flag|=elem[n].milyen;
	}
}

vertexelement_t::vertexelement_t()
{

}

vertexelement_t::vertexelement_t(uint32 num,const stringhash& id,int fajta)
{
	milyen=fajta;
	elemnum=num;

	if (id.value==_Hash("float"))
		this->type=GL_FLOAT;
	else if (id.value==_Hash("byte"))
		this->type=GL_UNSIGNED_BYTE;
	else if (id.value==_Hash("short"))
		this->type=GL_UNSIGNED_SHORT;
	else
	{
		ASSERTTXT(0,"unsupported vertex element type");
	}

	int mul;

	if (type==GL_FLOAT)
		mul=4;
	else if (GL_UNSIGNED_BYTE)
		mul=1;
	else if (GL_UNSIGNED_SHORT)
		mul=2;
	else
	{
		ASSERTTXT(0,"unsupported vertex element type");
		mul=4;
	}

	size=elemnum*mul;
}
